package com.lyz.controller;

import com.lyz.annotations.Auth;
import com.lyz.models.Session;
import com.lyz.models.User;
import com.lyz.models.UserLoginDTO;
import com.lyz.models.UserVO;
import com.lyz.services.SessionService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    HashMap<String, User> userHashMap = new HashMap<String, User>() {
        {
            put("123456", new User()
                    .setId(1)
                    .setAccount("123456")
                    .setPassword("456789")
                    .setName("张三")
                    .setPermission("admin"));
            put("456789", new User()
                    .setId(2)
                    .setAccount("456789")
                    .setPassword("123456")
                    .setName("李四")
                    .setPermission("user"));
        }
    };

    private final SessionService<UserVO> sessionService;

    public UserController(SessionService<UserVO> sessionService) {
        this.sessionService = sessionService;
    }

    @PostMapping("/login")
    public void login(HttpServletRequest request, @RequestBody UserLoginDTO loginDTO) {
        // 根据 account 从数据库查询对应的用户信息
        User user = userHashMap.get(loginDTO.getAccount());
        // 如果不存在，提醒账号不存在
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        // 存在，密码一致，登录成功，用户信息存到 session
        if (user.getPassword().equals(loginDTO.getPassword())) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            Session<UserVO> session = sessionService.login(userVO);
            session.setAttribute("permission", user.getPermission());
            sessionService.saveSession(session);
            return;
        }
        // 存在，密码不一致，登录失败
        throw new RuntimeException("登录失败");
    }

    @Auth("admin")
    @GetMapping("/info")
    public User info(HttpServletRequest request) {
        Session<UserVO> session = sessionService.getSession();
        Integer userId = session.getUserInfo().getId();
        if (Objects.isNull(userId)) {
            throw new RuntimeException("未登录");
        }
        List<User> users = userHashMap.values().stream().filter(u -> u.getId().equals(userId)).collect(Collectors.toList());
        if (users.isEmpty()) {
            throw new RuntimeException("未登录");
        }
        return users.get(0);
    }

}
